public class Solution124 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int max=Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        dfs(root);
        return max;
    }

    private int dfs(TreeNode root) {
        if (root==null){
            return 0;
        }
        int cur=root.val;
        int l=dfs(root.left);
        int r=dfs(root.right);
        int t=cur;
        if (l>0){
            t=t+l;
        }
        if (r>=0){
            t=t+r;
        }
        max=Math.max(max,t);
        cur+=Math.max(0,Math.max(l,r));
        return cur;
    }

    public static void main(String[] args) {
        System.out.println(new Solution124().maxPathSum(new TreeNode(9,new TreeNode(6),new TreeNode(-3,new TreeNode(-6),new TreeNode(2,new TreeNode(2),null)))));
    }
}
